import { PoisAction, PoisActionTypes } from '../actions/pois.action';
import { Poi, PlaceTextOption } from '../../../ngx-ol/models';

export interface PoisState {
    entities: { [id: string]: Poi };
    selected: Poi;
    keywords: PlaceTextOption;
    loaded: boolean;
    loading: boolean;
}

export const initialPoisState: PoisState = {
    entities: {},
    selected: null,
    keywords: null,
    loaded: false,
    loading: false
};

export function poisReducer(state: PoisState = initialPoisState, action: PoisAction): PoisState {
    switch(action.type) {
        case PoisActionTypes.LOAD_POIS: {
            return {
                ...state,
                loading: true,
                keywords: action.payload
            };
        }
        case PoisActionTypes.LOAD_POIS_FAIL: {
            return {
                ...state,
                loading: false,
                loaded: false
            };
        }
        case PoisActionTypes.LOAD_POIS_SUCCESS: {
            const pois = action.payload;
            const entities = pois.reduce((entities: { [id: string]: Poi }, poi: Poi) => {
                return {
                    ...entities,
                    [poi.id]: poi
                }
            }, {});
            return {
                ...state,
                loaded: true,
                loading: false,
                entities
            }
        }
        case PoisActionTypes.SELECT_POIS: {
            return {
                ...state,
                selected: action.payload
            }
        }
        case PoisActionTypes.Clear_POIS: {
            return initialPoisState;
        }
        default: {
            return state;
        }
    }
}